<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!--@selection-change多选按钮绑定事件-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope"><!--scope有整行数据-->
         <span style="color: #11b95c" v-if="scope.row.state == 1">启用</span>
         <span style="color: crimson" v-else-if="scope.row.state == 0">禁用</span>
         <span style="color: #8c939d" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
      <!--
      scope.$index：当前列的索引
      scope.row：当前行的数据
      -->
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <!--rules：表单校验规则
      editForm:表单引用名字
    -->
    <el-dialog title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
       <!--   <el-input v-model="editForm.manager" auto-complete="off"></el-input>-->

          <!--单选下拉框-->
            <el-select clearable v-model="editForm.manager" value-key="id" placeholder="请选择">
              <el-option
                  v-for="employee in employees"
                  :key="employee.id"
                  :label="employee.username"
                  :value="employee">
                <span style="float: left">{{ employee.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.phone }}</span>
              </el-option>
            </el-select>

        </el-form-item>
        <el-form-item label="上级部门">
         <!-- <el-input v-model="editForm.parent" auto-complete="off"></el-input>-->
          <!--options绑定的部门数组-->
          <el-cascader v-model="editForm.parent"
              :options="treeDepartments"
              :props="{
                checkStrictly: true,
                value:'id',
                label:'name'
              }"
              clearable></el-cascader>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

export default {
  data() {
    return {
      treeDepartments:[],
      employees:[],
      title:"",
      filters: {
        keyword: ''
      },
      departments: [],
      total: 0,
      currentPage: 1,
      pageSize:5,
      listLoading: false,
      sels: [],//列表选中行

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }, //失去焦点触发校验规则
          { min: 2, max: 4, message:'长度在3 至 5个字符', trigger: 'blur'}
        ],
        sn: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      editForm: {
        id:null,
        name:'',
        sn:'',
        state: 1,
        parent:null,
        manager:null
      }

    }
  },
  methods: {
    /*关键字查询处理方法*/
    search(){
      /*把当前页设置为第一页
      * 调用获取数据的方法
      * */
      this.currentPage = 1;
      this.getDepartments();
    },
    //性别显示转换
    formatState: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      this.listLoading = true;
      /*请求后端分页数据*/
      this.$http.post("/dept",para)
          .then(res =>{//处理请求成功的回调函数
            this.listLoading = false;//关闭页面加载（忙等）
            this.departments = res.data.list
            this.total = res.data.total
          }).catch(res =>{//处理请求失败的回调
            this.$message.error("网络异常")
          })

    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {//点击确认以后的处理逻辑·
        this.listLoading = true;
        //NProgress.start();
       this.$http.delete("/dept/"+row.id).then(res =>{
         if(res.data.success){//后台返回成功
           this.$message.success(res.data.message);
         }else{//后台返回失败
           this.$message.error(res.data.message);
         }
         this.currentPage = 1;//定位到第一页
         this.getDepartments();//1.跳转上一页2.定位到第一页

       }).catch(res =>{
         this.$message.error("网络异常")
       })

      }).catch(() => {//点击取消以后的处理逻辑·

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.getTree();
      if(this.$refs['editForm']) {
        this.$refs['editForm'].resetFields();//取消表单校验提示
      }
        this.title = "编辑";
        this.editFormVisible = true;//显示对话框
        this.editForm = Object.assign({}, row);//对象复制 回显数据
    },
    //显示新增界面
    handleAdd: function () {
      this.getTree();
      if(this.$refs['editForm']) {
        this.$refs['editForm'].resetFields();//取消表单校验提示
      }
      this.title = "新增";
      this.editFormVisible = true;
      this.editForm = {//清空表单
        id:null,
        name:'',
        sn:'',
        state: 1,
        parent:null,
        manager:null
      };
    },
    //编辑
    /*
    * this.$refs.editForm.validate()获取指定表单editForm主动发起校验
    *
    * */
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);//克隆
            //处理提交的数据
            let paraArr = para.parent;
            if(paraArr){//选择父部门，才执行下面的逻辑
              let parent = {id: paraArr[paraArr.length -1]}//后端的department实体类中需要parent对象
              para.parent = parent;
            }
            //提交表单
            this.$http.put("dept",para).then(res => {

              this.editLoading = false;//关闭提交按钮忙等

              if(res.data.success){//后台返回成功
                this.editFormVisible = false;//关闭对话框
                this.$message.success(res.data.message);
              }else{//后台返回失败
                this.$message.error(res.data.message);
              }
              this.currentPage = 1;//定位到第一页
              this.getDepartments();//1.跳转上一页2.定位到第一页\
              this.$refs['editForm'].resetFields();

            }).catch(res =>{
              this.editLoading = false;//关闭提交按钮忙等
              this.$message.error("网络异常")

            })
            /*editDepartment(para).then((res) => {
              this.editLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.getDepartments();
            });*/
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;/*勾选上装如sels数组*/
    },
    //批量删除
    batchRemove: function () {
      /*把选中行数组对象转换成 去每个对象里的id转成数组*/
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        /*发起批量删除请求*/
        this.$http.patch("/dept",ids).then(res =>{
          if(res.data.success){//后台返回成功
            this.$message.success(res.data.message);
          }else{//后台返回失败
            this.$message.error(res.data.message);
          }
          this.currentPage = 1;//定位到第一页
          this.getDepartments();//1.跳转上一页2.定位到第一页

        }).catch(res =>{
          this.$message.error("网络异常")
        })
      }).catch(() => {

      });
    },getEmployees(){
      this.$http.get("/emp").then( res =>{
        this.employees = res.data;
      }).catch(res =>{
        this.$message.error("获取员工数据失败")
      })
    },
    getTree(){//获取部门树的方法
      this.$http.get("/dept/getTree").then(res => {
        this.treeDepartments = res.data;
      }).catch(res =>{
        this.$message.error("查询部门树失败")
      })

    }
  },
  mounted() {
    this.getDepartments();
    this.getEmployees();//在页面加载完成就获取所有员工
  }
}

</script>

<style scoped>

</style>